aa<template>
  <div class="post-detail-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    
    <!-- 错误提示 -->
    <el-alert
      v-if="error"
      :title="error"
      type="error"
      :closable="false"
      show-icon
    />
    
    <!-- 帖子内容 -->
    <div v-if="post && !loading" class="post-content">
      <h1 class="post-title">{{ post.title }}</h1>
      
      <div class="post-meta">
        <div class="author-info">
          <el-avatar :src="post.user.avatar" :size="40">
            <el-icon><User /></el-icon>
          </el-avatar>
          <div class="author-details">
            <div class="author-name">{{ post.user.username }}</div>
            <div class="post-time">{{ formatDate(post.createdAt) }}</div>
          </div>
        </div>
        
        <div class="post-stats">
          <span><el-icon><View /></el-icon> {{ post.views || 0 }}</span>
          <span><el-icon><ChatDotRound /></el-icon> {{ post.comments?.length || 0 }}</span>
          <span @click="toggleLike" :class="{ 'liked': isLiked }">
            <el-icon><Star /></el-icon> {{ post.likes?.length || 0 }}
          </span>
        </div>
      </div>
      
      <!-- 帖子标签 -->
      <div v-if="post.tags && post.tags.length > 0" class="post-tags">
        <el-tag 
          v-for="tag in post.tags" 
          :key="tag" 
          size="small" 
          effect="plain"
          class="tag-item"
        >
          {{ tag }}
        </el-tag>
      </div>
      
      <!-- 帖子正文 -->
      <div class="post-body">
        {{ post.content }}
      </div>
      
      <!-- 帖子图片 -->
      <div v-if="post.images && post.images.length > 0" class="post-images">
        <el-image 
          v-for="(image, index) in post.images" 
          :key="index"
          :src="getImageUrl(image)"
          :preview-src-list="post.images.map(img => getImageUrl(img))"
          fit="cover"
          class="post-image"
        />
      </div>
      
      <!-- 操作按钮 -->
      <div v-if="isOwner" class="post-actions">
        <el-button type="primary" plain @click="editPost">编辑</el-button>
        <el-button type="danger" plain @click="confirmDelete">删除</el-button>
      </div>
      
      <!-- 评论区 -->
      <div class="comments-section">
        <h3>评论 ({{ post.comments?.length || 0 }})</h3>
        
        <!-- 评论表单 -->
        <div v-if="isLoggedIn" class="comment-form">
          <el-input
            v-model="commentText"
            type="textarea"
            :rows="3"
            placeholder="写下你的评论..."
            maxlength="500"
            show-word-limit
          />
          <div class="form-actions">
            <el-button type="primary" @click="submitComment" :loading="submittingComment">
              发表评论
            </el-button>
          </div>
        </div>
        <div v-else class="login-prompt">
          <el-alert
            title="请先登录后再发表评论"
            type="info"
            :closable="false"
            show-icon
          >
            <template #default>
              <router-link to="/login" class="login-link">点击登录</router-link>
            </template>
          </el-alert>
        </div>
        
        <!-- 评论列表 -->
        <div v-if="post.comments && post.comments.length > 0" class="comments-list">
          <div v-for="comment in post.comments" :key="comment._id" class="comment-item">
            <div class="comment-avatar">
              <el-avatar :src="comment.user.avatar || '/default-avatar.png'" :size="32" />
            </div>
            <div class="comment-content">
              <div class="comment-header">
                <span class="comment-author">{{ comment.user.username }}</span>
                <span class="comment-time">{{ formatDate(comment.createdAt) }}</span>
              </div>
              <div class="comment-text">{{ comment.text }}</div>
              <div class="comment-actions">
                <span @click="likeComment(comment)" :class="{ 'liked': comment.isLiked }">
                  <el-icon><ThumbUp /></el-icon> {{ comment.likes?.length || 0 }}
                </span>
                <span @click="replyToComment(comment)">
                  <el-icon><ChatLineRound /></el-icon> 回复
                </span>
              </div>
            </div>
          </div>
        </div>
        <div v-else-if="!loading" class="no-comments">
          暂无评论，快来发表第一条评论吧！
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
// 移除 ThumbUp, 添加 StarFilled
import { View, ChatDotRound, Star, StarFilled, ChatLineRound } from '@element-plus/icons-vue' 
import axios from '@/services/axios'

const route = useRoute()
const router = useRouter()
const store = useStore()

const postId = computed(() => route.params.id)
const post = ref(null)
const loading = ref(true)
const error = ref(null)
const commentText = ref('')
const submittingComment = ref(false)
const isLiked = ref(false)

// 计算属性
const isLoggedIn = computed(() => store.getters['auth/isAuthenticated'])
const currentUser = computed(() => store.getters['auth/user'])
const isOwner = computed(() => {
  return isLoggedIn.value && post.value && currentUser.value && 
         post.value.user._id === currentUser.value._id
})

// 获取帖子详情
const fetchPostDetails = async () => {
  loading.value = true
  error.value = null
  
  try {
    const response = await axios.get(`/api/posts/${postId.value}`)
    post.value = response.data.post
    
    // 如果用户已登录，获取交互状态
    if (isLoggedIn.value) {
      fetchInteractionStatus()
    }
  } catch (err) {
    console.error('获取帖子详情失败:', err)
    error.value = err.response?.data?.error || '获取帖子详情失败'
  } finally {
    loading.value = false
  }
}

// 获取交互状态（点赞等）
const fetchInteractionStatus = async () => {
  try {
    const response = await axios.get(`/api/posts/${postId.value}/interaction`)
    isLiked.value = response.data.isLiked
  } catch (err) {
    console.error('获取交互状态失败:', err)
  }
}

// 点赞/取消点赞
const toggleLike = async () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录后再点赞')
    return
  }
  
  try {
    const response = await axios.post(`/api/posts/${postId.value}/like`)
    isLiked.value = response.data.liked
    
    // 更新点赞数
    if (post.value && post.value.likes) {
      if (isLiked.value) {
        // 如果当前是点赞状态，但原来没有当前用户的ID，则添加
        if (!post.value.likes.includes(currentUser.value._id)) {
          post.value.likes.push(currentUser.value._id)
        }
      } else {
        // 如果当前是取消点赞状态，则移除当前用户ID
        const index = post.value.likes.indexOf(currentUser.value._id)
        if (index > -1) {
          post.value.likes.splice(index, 1)
        }
      }
    }
  } catch (err) {
    console.error('点赞操作失败:', err)
    ElMessage.error(err.response?.data?.error || '操作失败')
  }
}

// 提交评论
const submitComment = async () => {
  if (!commentText.value.trim()) {
    ElMessage.warning('评论内容不能为空')
    return
  }
  
  submittingComment.value = true
  
  try {
    const response = await axios.post('/api/comments', {
      text: commentText.value.trim(),
      targetId: postId.value,
      targetType: 'post'
    })
    
    // 添加新评论到列表
    if (!post.value.comments) {
      post.value.comments = []
    }
    post.value.comments.unshift(response.data.comment)
    
    // 清空评论框
    commentText.value = ''
    ElMessage.success('评论发表成功')
  } catch (err) {
    console.error('发表评论失败:', err)
    ElMessage.error(err.response?.data?.error || '发表评论失败')
  } finally {
    submittingComment.value = false
  }
}

// 点赞评论
const likeComment = async (comment) => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录后再点赞')
    return
  }
  
  try {
    const response = await axios.post(`/api/comments/${comment._id}/like`)
    
    // 更新评论的点赞状态
    comment.isLiked = response.data.liked
    
    // 更新点赞数
    if (response.data.liked) {
      if (!comment.likes) comment.likes = []
      if (!comment.likes.includes(currentUser.value._id)) {
        comment.likes.push(currentUser.value._id)
      }
    } else {
      const index = comment.likes.indexOf(currentUser.value._id)
      if (index > -1) {
        comment.likes.splice(index, 1)
      }
    }
  } catch (err) {
    console.error('点赞评论失败:', err)
    ElMessage.error(err.response?.data?.error || '操作失败')
  }
}

// 回复评论
const replyToComment = (comment) => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录后再回复')
    return
  }
  
  // 在评论框中添加@用户名
  commentText.value = `@${comment.user.username} `
  // 聚焦到评论框
  document.querySelector('.comment-form textarea').focus()
}

// 编辑帖子
const editPost = () => {
  router.push(`/post/edit/${postId.value}`)
}

// 确认删除帖子
const confirmDelete = () => {
  ElMessageBox.confirm(
    '确定要删除这篇帖子吗？此操作不可恢复。',
    '删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deletePost()
  }).catch(() => {
    // 用户取消删除
  })
}

// 删除帖子
const deletePost = async () => {
  try {
    await axios.delete(`/api/posts/${postId.value}`)
    ElMessage.success('帖子已删除')
    router.push('/community') // 跳转到社区页面
  } catch (err) {
    console.error('删除帖子失败:', err)
    ElMessage.error(err.response?.data?.error || '删除失败')
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  
  const date = new Date(dateString)
  const now = new Date()
  const diff = now - date
  
  // 小于1分钟
  if (diff < 60 * 1000) {
    return '刚刚'
  }
  
  // 小于1小时
  if (diff < 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 1000))}分钟前`
  }
  
  // 小于24小时
  if (diff < 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
  }
  
  // 小于30天
  if (diff < 30 * 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`
  }
  
  // 大于30天，显示具体日期
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

onMounted(() => {
  fetchPostDetails()
})

// 将相对路径转换为完整的图片 URL
const getImageUrl = (relativePath) => {
  if (!relativePath) return ''; // 如果没有路径，返回空字符串
  // 假设后端服务运行在 localhost:3000
  // 在生产环境中，应该使用配置的基础 URL
  const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000'; 
  return `${baseUrl}${relativePath}`;
};
 </script>
 
 <style scoped>
.post-detail-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.loading-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.post-content {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.post-title {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.post-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-details {
  display: flex;
  flex-direction: column;
}

.author-name {
  font-weight: 500;
  color: #303133;
}

.post-time {
  font-size: 12px;
  color: #909399;
}

.post-stats {
  display: flex;
  gap: 16px;
  color: #606266;
  font-size: 14px;
}

.post-stats span {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
}

.post-stats .liked {
  color: #409EFF;
}

.post-tags {
  margin-bottom: 16px;
}

.tag-item {
  margin-right: 8px;
  margin-bottom: 8px;
}

.post-body {
  margin-bottom: 24px;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}

.post-images {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 8px;
  margin-bottom: 24px;
}

.post-image {
  width: 100%;
  height: 150px;
  border-radius: 4px;
  object-fit: cover;
}

.post-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-bottom: 24px;
  padding-top: 16px;
  border-top: 1px solid #EBEEF5;
}

.comments-section {
  margin-top: 32px;
}

.comments-section h3 {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.comment-form {
  margin-bottom: 24px;
}

.form-actions {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
}

.login-prompt {
  margin-bottom: 24px;
}

.login-link {
  color: #409EFF;
  text-decoration: none;
}

.comments-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.comment-item {
  display: flex;
  gap: 12px;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
}

.comment-author {
  font-weight: 500;
  color: #303133;
}

.comment-time {
  font-size: 12px;
  color: #909399;
}

.comment-text {
  margin-bottom: 8px;
  line-height: 1.5;
}

.comment-actions {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #909399;
}

.comment-actions span {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
}

.comment-actions .liked {
  color: #409EFF;
}

.no-comments {
  color: #909399;
  text-align: center;
  padding: 24px 0;
}
</style>